package com.moxigua.iotbox.func.setting;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.moxigua.iotbox.R;
import com.moxigua.iotbox.base.BaseActivity;
import com.moxigua.iotbox.base.BaseApplication;
import com.moxigua.iotbox.base.Constants;
import com.moxigua.iotbox.bean.BaseRequest;
import com.moxigua.iotbox.bean.MqttAction;
import com.moxigua.iotbox.func.MqttClientHepler;
import com.moxigua.iotbox.func.MqttService;
import com.moxigua.iotbox.func.event.BaseEvent;
import com.moxigua.iotbox.util.SPUtils;
import com.orhanobut.logger.Logger;
import com.squareup.picasso.Picasso;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

public class SettingsActivity extends BaseActivity {

    @BindView(R.id.iv_online_status)
    ImageView mIvOnlineStatus;
    @BindView(R.id.tv_online_status)
    TextView mTvOnlineStatus;
    @BindView(R.id.et_server)
    EditText mEtServer;
    @BindView(R.id.et_user)
    EditText mEtUser;
    @BindView(R.id.et_pass)
    EditText mEtPass;
    @BindView(R.id.et_clientid)
    EditText mEtClientid;
    @BindView(R.id.btn_connect)
    Button mBtnConnect;
    @BindView(R.id.btn_disconnect)
    Button mBtnDisconnect;
    @BindView(R.id.iv_back)
    ImageView mIvBack;

    String mEndpoint;
    String mUser;
    String mPass;
    String mClientId;



    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        String server = TextUtils.isEmpty((String) SPUtils.get(Constants.SP_ENDPOINT, "")) ? Constants.DEFAULT_ENDPOINT : (String) SPUtils.get(Constants.SP_ENDPOINT, "");
        String user = TextUtils.isEmpty((String) SPUtils.get(Constants.SP_USER, "")) ? Constants.DEFAULT_USER : (String) SPUtils.get(Constants.SP_USER, "");
        String pass = TextUtils.isEmpty((String) SPUtils.get(Constants.SP_PASS, "")) ? Constants.DEFAULT_PASS : (String) SPUtils.get(Constants.SP_PASS, "");
        int clientId = (int) SPUtils.get(Constants.SP_CLIENT_ID, 0);
        mEtServer.setText(server);
        mEtUser.setText(user);
        mEtPass.setText(pass);
        mEtClientid.setText(String.valueOf(clientId));
        getOnlineStatus();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_settings;
    }

    @OnClick({R.id.btn_connect, R.id.btn_test_connect, R.id.btn_disconnect, R.id.iv_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_connect:
                //连接服务器
                mEndpoint = mEtServer.getText().toString().trim();
                mUser = mEtUser.getText().toString().trim();
                mPass = mEtPass.getText().toString().trim();
                mClientId = mEtClientid.getText().toString().trim();

                if (TextUtils.isEmpty(mEndpoint) || TextUtils.isEmpty(mUser) || TextUtils.isEmpty(mPass)|| TextUtils.isEmpty(mClientId)) {
                    showShortToast("请完整填写！");
                    return;
                }
                spSave();
                startService(new Intent(mContext, MqttService.class));
                showLoadingDialog();
                break;
            case R.id.btn_test_connect:
                //测试连接设备
                if (MqttClientHepler.getInstance().isConnect()) {
                    testConnect();
                } else {
                    showShortToast("请先连接服务器！");
                }

                break;
            case R.id.btn_disconnect:
                try {
                    if (MqttClientHepler.getInstance().isConnect()) {
                        MqttClientHepler.getInstance().disconnect();
                        setOnlineStatus(false);
                        showShortToast("已经断开连接");
                    } else {
                        showShortToast("尚未连接服务器");
                    }
                } catch (MqttException e) {
                    e.printStackTrace();
                    showShortToast("出错！稍后再试！");
                }
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * 存储信息到SP文件
     */
    private void spSave() {
        SPUtils.put(Constants.SP_ENDPOINT, mEndpoint);
        SPUtils.put(Constants.SP_USER, mUser);
        SPUtils.put(Constants.SP_PASS, mPass);
        SPUtils.put(Constants.SP_CLIENT_ID,Integer.valueOf(mClientId));
        Logger.d(SPUtils.get(Constants.SP_CLIENT_ID, 999));
    }

    private void getOnlineStatus() {
        if (BaseApplication.isOnline()) {
            setOnlineStatus(true);
        } else {
            setOnlineStatus(false);
        }
    }

    private void setOnlineStatus(boolean isOnline) {
        Logger.d("设备状态变化！");
        if (isOnline) {
            mTvOnlineStatus.setText(R.string.online);
            Picasso.with(mContext)
                    .load(R.drawable.yes)
                    .into(mIvOnlineStatus);
            if (!BaseApplication.isOnline()) {
                showShortToast("设备在线");
                BaseApplication.setIsOnline(true);
            }
        } else {
            mTvOnlineStatus.setText(R.string.offline);
            Picasso.with(mContext)
                    .load(R.drawable.no)
                    .into(mIvOnlineStatus);
            showShortToast("设备离线");
            BaseApplication.setIsOnline(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseEvent(BaseEvent event) {
        Logger.d("收到信息："+event.toString());
        switch (event.topic) {
            case Constants.TOPIC_NOR_CON_SUC:
                //连接成功，测试在线
                mLoadingDialog.loadSuccess();
                showShortToast("服务器连接成功，正在测试设备是否在线");
                testConnect();  //测试设备在线
                break;
            case Constants.TOPIC_ERR_NOCONFIG:
            case Constants.TOPIC_ERR_CON_FAILD:
                //没有配置文件的情况与连接失败的情况
                mLoadingDialog.loadFailed();
                showShortToast(event.toString());
                break;
            case Constants.TOPIC_SUB_REMOTE:
                Logger.d(event.message.toString());
                String json = event.message.toString();
                if (json.contains("\"Online\"")){
                    setOnlineStatus(true);
                } else if (json.contains("\"OffOnline\"")) {
                    setOnlineStatus(false);
                }
                break;
        }
    }

    private void testConnect() {
        MqttAction<BaseRequest,Double> requestOnlineAction = new MqttAction<>();
        requestOnlineAction.setMetric(Constants.METRIC_REQUEST_ONLINE);
        requestOnlineAction.setValue(Double.valueOf(0));
        BaseRequest requestOnline = new BaseRequest();
        int randomPacketId = (int) (Math.random() * 10000);
        BaseApplication.setLastPacketId(randomPacketId);
        requestOnline.setPacketID(randomPacketId);
        requestOnline.setClientid((Integer) SPUtils.get(Constants.SP_CLIENT_ID,0));
        requestOnlineAction.setTags(requestOnline);
        String payload = "[" + new Gson().toJson(requestOnlineAction) + "]";
        Logger.d(payload);
        MqttClientHepler.getInstance().publish(Constants.TOPIC_PUB_SET, 1, payload.getBytes());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
